/**
 * @copyright Copyright (c) 2025 
 * CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author xxxcsg
 * @brief 鹰眼组件工具接口
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <errno.h>
#include <pthread.h>
#include "eagle_eys_server.h"



static BusinessHandle *myHandle;
static int quit = 0;

#define MAX_EVENTS 10
#define PORT 6543
#define BUFFER_SIZE 1024


// 发送响应给客户端
void send_response(int client_socket,  EagleEysBusinessPackage *response) {
    if (send(client_socket, (char*)response, sizeof(response)+response->len, 0) < 0) {
        perror("Send failed");
    }
}

void handle_get_power_mesg(int client_socket)
{
    EagleEysBusinessPackage *package = NULL;
    float power = 0.0;
    int ret = 0;
    if(myHandle->powerMesgFunc != NULL)
    {
        ret = myHandle->powerMesgFunc(&power);
        if(!ret)
        {
            package = (EagleEysBusinessPackage*)malloc(sizeof(EagleEysBusinessPackage) + sizeof(power));
            package->type = GET_POWER_INFO;
            package->len = sizeof(power);
            memcpy(package->data, &power, sizeof(power));
        }
        else
        {
            package = (EagleEysBusinessPackage*)malloc(sizeof(EagleEysBusinessPackage));
            package->type = GET_POWER_INFO;
            package->len = 0;
        }

        send_response(client_socket, package);
        free(package);
    }
    else
    {
        printf("powerMesgFunc is null\n");
    }
}

void handle_get_module_mesg(int client_socket)
{
    EagleEysBusinessPackage *package = NULL;
    ModuleMesg mesg = {0};
    int ret = 0;

    if(myHandle->moduleMesgFunc != NULL)
    {
        ret = myHandle->moduleMesgFunc(&mesg);

        if(!ret)
        {
            package = (EagleEysBusinessPackage*)malloc(sizeof(EagleEysBusinessPackage) + sizeof(mesg));
            package->type = GET_4G_MODULE_INFO;
            package->len = sizeof(mesg);
            memcpy(package->data, &mesg, sizeof(mesg));
        }
        else
        {
            package = (EagleEysBusinessPackage*)malloc(sizeof(EagleEysBusinessPackage));
            package->type = GET_4G_MODULE_INFO;
            package->len = 0;
        }

        send_response(client_socket, package);
        free(package);
    }
    else
    {
        printf("moduleMesgFunc is NULL\n");
    }
   
}

void handle_get_login_mesg(int client_socket)
{
    EagleEysBusinessPackage *package = NULL;
    LoginMesg mesg = {0};
    int ret = 0;

    if(myHandle->loginMesgFunc != NULL)
    {
        ret = myHandle->loginMesgFunc(&mesg);

        if(!ret)
        {
            package = (EagleEysBusinessPackage*)malloc(sizeof(EagleEysBusinessPackage) + sizeof(mesg));
            package->type = GET_LOGIN_INFO;
            package->len = sizeof(mesg);
            memcpy(package->data, &mesg, sizeof(mesg));
        }
        else
        {
            package = (EagleEysBusinessPackage*)malloc(sizeof(EagleEysBusinessPackage));
            package->type = GET_LOGIN_INFO;
            package->len = 0;
        }
    }
    else
    {
        printf("loginMesgFunc is NULL\n");
        package = (EagleEysBusinessPackage*)malloc(sizeof(EagleEysBusinessPackage));
        package->type = GET_LOGIN_INFO;
        package->len = 0;
    }

    send_response(client_socket, package);
    free(package);
}

void* handle_client(void* arg) 
{
    int client_socket = *(int*)arg;
    free(arg); // Free the argument memory as it's no longer needed

    char buffer[BUFFER_SIZE];
    EagleEysBusiness recvMesg = {0};
    ssize_t bytes_received = 0;
    EagleEysBusinessPackage tmp = {0};
    while( (bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0)))
    {
        // printf("Received from client: len:%ld\n", bytes_received);

         recvMesg = *(EagleEysBusiness*)buffer;

        switch (recvMesg.type)
        {
        case GET_4G_MODULE_INFO:
            // printf("get 4g module mesg\n");
            handle_get_module_mesg(client_socket);
            break;
        case GET_POWER_INFO:
            // printf("get power mesg\n");
            handle_get_power_mesg(client_socket);
            break;
        case GET_LOGIN_INFO:
            // printf("get login mesg\n");
            handle_get_login_mesg(client_socket);
            break;
        default:
            // printf("unknow mesg type\n");
            
            tmp.type = UNKNOWN_TYPE;
            tmp.len = 0;
            send_response(client_socket, &tmp);
            break;
        }
    }
    if (bytes_received == -1) {
        perror("recv");
    }

    close(client_socket);
    pthread_exit(NULL);
    
}

void* EagleEyeServer(void* arg) 
{
    int server_socket = 0, client_socket = 0;
    struct sockaddr_in server_addr;
    // socklen_t addr_len = sizeof(server_addr);
    pthread_t thread_id;

    // 创建服务器socket
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("Socket creation failed");
        quit = 2;
        return NULL;
    }

    // 设置地址结构
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT);

    // 绑定套接字
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("Binding failed");
        quit = 3;
        return NULL;

    }

    // 监听连接
    if (listen(server_socket, 5) == -1) {
        perror("Listening failed");
        quit = 4;
        return NULL;
    }

    while (1) {
        // 接受客户端连接
        client_socket = accept(server_socket, NULL, NULL);
        if (client_socket == -1) {
            perror("Accept failed");
            continue;
        }

        // 为每个客户端创建一个新线程
        int* client_socket_ptr = malloc(sizeof(int));
        *client_socket_ptr = client_socket;
        if (pthread_create(&thread_id, NULL, handle_client, (void*)client_socket_ptr) != 0) {
            perror("Thread creation failed");
            close(client_socket);
            continue;
        }
    }

    // 清理资源
    close(server_socket);
    quit = 1;
    return NULL;
}


int EagleEyeServerInit(BusinessHandle *handle)
{
    pthread_t thread_id;
    // void* thread_result;
    int ret = 0;

    if(handle == NULL)
    {
        perror("Error handle is NULL");
        return 1;
    }
    if(myHandle)
    {
        perror("func has been reg");
        return 1;
    }

    myHandle = handle;

     // 创建线程
    if (pthread_create(&thread_id, NULL, EagleEyeServer, NULL) != 0) {
        perror("Error creating thread");
        return 1;
    }

    // 等待线程结束 阻塞
    // if (pthread_join(thread_id, &thread_result) != 0) {
    //     perror("Error joining thread");
    //     return 1;
    // }

    sleep(1);

    ret = quit;
    return ret;
}
